package net.lovesrc.support.service.imageverifycode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.zhouzhou.fastjava.BizException;
import com.zhouzhou.fastjava.util.StringKit;


import java.io.InputStream;

public class FeiFeiImageVerifyCodeService implements ImageVerifyCodeService {

    private String pdId;

    private String pdKey;

    public FeiFeiImageVerifyCodeService(String pdId, String pdKey) {
        this.pdId = pdId;
        this.pdKey = pdKey;
    }

    @Override
    public String recoginze(String contentType, InputStream is) {
        return this.recoginze("30400", contentType, is);
    }

    @Override
    public String recoginze(String type, String contentType, InputStream is) {
        long timestamp = System.currentTimeMillis() / 1000;
        String sign = StringKit.md5(pdId + timestamp + StringKit.md5(timestamp + pdKey));
        String resText = HttpRequest.post("http://pred.fateadm.com/api/capreg")
                .part("user_id", pdId)
                .part("timestamp", timestamp)
                .part("sign", sign)
                .part("predict_type", type)
                .part("up_type", "mt")
                .part("img_data", String.valueOf(System.currentTimeMillis()), contentType, is)
                .body();
        JSONObject resJson = JSON.parseObject(resText);
        int retCode = resJson.getIntValue("RetCode");
        if (retCode != 0) {
            throw BizException.messageOf(resJson.getString("ErrMsg"));
        }
        JSONObject rspData = resJson.getJSONObject("RspData");
        return rspData.getString("result");
    }

}
